在graphQL中,假如我們要去修改資料或是新增資料,我們會使用到mutation這個type而非query。
今天,我們在mutation下做一個新增Post的功能:
app/graphql/types/mutation_type.rb
module Types
  class MutationType < BaseObject
    field :create_post, mutation: Mutations::CreatePost
  end
end
/app/graphql/專案名稱_schema.rb中,必須確定有將mutation加入,不然會無法使用。class GraphqlApiSchema < GraphQL::Schema
  mutation(Types::MutationType)
  query(Types::QueryType)
end
app/graphql/mutations/base_mutation.rb以及app/graphql/mutations/create_post.rb,其中BaseMutation是讓CreatePost繼承的。module Mutations
  class BaseMutation < GraphQL::Schema::Mutation
    null false
  end
end
module Mutations
  class CreatePost < BaseMutation
    argument :title, String, required: true
    argument :content, String, required: true
  
    type Types::PostType
  
    def resolve(title: nil, content: nil)
      Post.create!(
        title: title,
        content: content,
      )
    end
  end
end
在CreatePost中,用了argument方法去定義了mutation中參數的型別以及是否必填,type方法定義了回傳的type,而在resolve方法中,實現了新增功能,以及回傳我們新增的資料,這兩件事。
app/graphql/types/mutation_type.rb
module Types
  class MutationType < BaseObject
    field :create_post, mutation: Mutations::CreatePost
  end
end
於是,一個簡單的mutation便完成了。
在graphiql中,我們輸入以下查詢:
mutation {
  createPost (
    title: 'new title',
    content: 'new content',
  ){
    title
    content
  }
}
便會完成新增資料,以及回傳新增的資料。